<template>
  <div class="app-container">
      <div class="filter-container">
          <el-input v-model="listQuery.title" placeholder="公告标题" style="width: 200px;" class="filter-item"
              @keyup.enter.native="handleFilter" />
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
              查询
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
              @click="handleCreate">
              新增文章
          </el-button>
      </div>

      <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
          style="width: 100%;" @sort-change="sortChange">
          <el-table-column label="ID" align="center" width="80">
              <template slot-scope="{row}">
                  <span>{{ row.id }}</span>
              </template>
          </el-table-column>
          <el-table-column label="文章标题" align="center">
              <template slot-scope="{row}">
                  <span>{{ row.title }}</span>
              </template>
          </el-table-column>
          <el-table-column label="文章简介" align="center">
              <template slot-scope="{row}">
                  <span>{{ row.desc }}</span>
              </template>
          </el-table-column>
          <el-table-column label="封面图片" align="center">
              <template slot-scope="{row}">
                <el-popover trigger="hover" placement="top">
                    <div><el-image style="width: 100px; height: 100px" :src="row.image"></el-image></div>
                    <div slot="reference" class="name-wrapper">
                      <el-tag size="medium">图片</el-tag>
                    </div>
                  </el-popover>
              </template>
          </el-table-column>
          <el-table-column label="时间" width="120px" align="center">
              <template slot-scope="{row}">
                  <span>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
          </el-table-column>
          <el-table-column label="文章类型" class-name="status-col" width="100">
              <template slot-scope="{row}">
                  <el-tag :type="row.types | statusFilter">
                      {{ row.types == 1 ? '行情分析' : row.types == 2 ? '热点分析' : '异常' }}
                  </el-tag>
              </template>
          </el-table-column>
          <el-table-column label="状态" class-name="status-col" width="100">
              <template slot-scope="{row}">
                  <el-tag :type="row.status | statusFilter">
                      {{ row.status == 1 ? '启用' : row.status == 2 ? '封禁' : '异常' }}
                  </el-tag>
              </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
              <template slot-scope="{row,$index}">
                  <el-button type="primary" size="mini" @click="handleUpdate(row)">
                      编辑
                  </el-button>
                  <el-button size="mini" type="danger" @click="handleDelete(row, $index)">
                      删除
                  </el-button>
              </template>
          </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
          @pagination="getList" />
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px">
          <el-form-item label="封面图片">
              <el-upload
                  class="avatar-uploader"
                  action="https://cs4.hephp.cn/api/Banlist/update"
                  :show-file-list="false"
                  :on-success="handleonsuccess">
                  <img v-if="temp.image" :src="temp.image" style="width:200px;height:200px;" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
          </el-form-item>
              <el-form-item label="标题" prop="title">
                  <el-input v-model="temp.title" />
              </el-form-item>
              <el-form-item label="简介" prop="desc">
                  <el-input v-model="temp.desc" />
              </el-form-item>
              <el-form-item label="文章类型" prop="types">
                <el-radio-group v-model="temp.types">
                  <el-radio :label="1">行情分析</el-radio>
                  <el-radio :label="2">热点咨询</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="详情" prop="contents">
                  <tinymce ref="editor" v-if="dialogFormVisible"  v-model="temp.contents" :height="160" />
                  <!-- <el-input type="textarea" :rows="5" v-model="temp.content" /> -->
              </el-form-item>
              <el-form-item label="状态">
                  <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
                      <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name"
                          :value="item.key" />
                  </el-select>
              </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">
                  取消
              </el-button>
              <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
                  {{ textMap[dialogStatus] }}
              </el-button>
          </div>
      </el-dialog>
  </div>
</template>
<script>
import { fetchList, createArticle, updateArticle, getDel } from '@/api/zx'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Tinymce from '@/components/Tinymce'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
const statusOptions = [
  { key: 1, display_name: '启用' },
  { key: 2, display_name: '封禁' }
]
export default {
  name: 'ComplexTable',
  components: { Pagination, Tinymce },
  directives: { waves },
  filters: {
      statusFilter(status) {
          const statusMap = {
              1: 'success',
              2: 'info',
              3: 'danger'
          }
          return statusMap[status]
      },
      typeFilter(type) {
          return calendarTypeKeyValue[type]
      }
  },
  data() {
      return {
          eid:'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + ''),
          tableKey: 0,
          list: null,
          total: 0,
          listLoading: true,
          listQuery: {
              page: 1,
              limit: 20,
              title: '',
          },
          importanceOptions: [1, 2, 3],
          statusOptions,
          showReviewer: false,
          temp: {
              id: undefined,
              title: '',
              contents: '',
              desc: '',
              types:1,
              status: 1,
              image:''
          },
          dialogFormVisible: false,
          dialogStatus: '',
          textMap: {
              update: '编辑',
              create: '发布文章'
          },
          dialogPvVisible: false,
          uList: [],
          pvData: [],
          rules: {
              // username: [{ required: true, message: '用户名不能为空', trigger: 'change' }],
              // password: [{ required: true, message: '密码不能为空', trigger: 'change' }],
              // strtime: [{ required: true, message: '授权开始时间不能为空', trigger: 'blur' }],
              // endtime: [{ required: true, message: '授权结束时间不能为空', trigger: 'blur' }],
              // codemacike: [{ required: true, message: '授权码不能为空', trigger: 'blur' }],
              // phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
              // email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }],
              // fynum: [{ required: true, message: '翻译次数不能为空', trigger: 'blur' }],
              // pnum: [{ required: true, message: '号码数量不能为空', trigger: 'blur' }],
              // status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
          },
          downloadLoading: false
      }
  },
  created() {
      this.getList()
  },
  methods: {
      getList() {
          this.listLoading = true
          fetchList(this.listQuery).then(response => {
              console.log(response.data)
              this.list = response.data.list
              this.total = response.data.count
              setTimeout(() => {
                  this.listLoading = false
              }, 1 * 1000)
          })
      },
      getUserLists() {
          getUserList().then(response => {
              console.log(response.data)
              this.uList = response.data
          })
      },
      handleFilter() {
          this.listQuery.page = 1
          this.getList()
      },
      handleModifyStatus(row, status) {
          this.$message({
              message: '操作Success',
              type: 'success'
          })
          row.status = status
      },
      sortChange(data) {
          const { prop, order } = data
          if (prop === 'id') {
              this.sortByID(order)
          }
      },
      sortByID(order) {
          if (order === 'ascending') {
              this.listQuery.sort = '+id'
          } else {
              this.listQuery.sort = '-id'
          }
          this.handleFilter()
      },
      resetTemp() {
          this.temp = {
              id: undefined,
              title: '',
              contents: '',
              types:1,
              desc: '',
              status: 1,
              image:''
          }
      },
      handleCreate() {
          this.resetTemp()
          this.dialogStatus = 'create'
          this.dialogFormVisible = true
          this.$nextTick(() => {
              this.$refs['dataForm'].clearValidate()
          })
      },
      createData() {
          this.$refs['dataForm'].validate((valid) => {
              if (valid) {
                  createArticle(this.temp).then(response => {
                      if (response.code == 200) {
                          this.getList()
                          this.dialogFormVisible = false
                          this.$notify({
                              title: 'Success',
                              message: 'Created Successfully',
                              type: 'success',
                              duration: 2000
                          })
                      } else {
                          this.$notify({
                              title: 'Success',
                              message: 'add none',
                              type: 'error',
                              duration: 2000
                          })
                      }
                  })
              }
          })
      },
      handleUpdate(row) {
          console.log('测试信息', row)
          this.temp = Object.assign({}, row) // copy obj
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
          // this.$router.replace({ path: '/gonggs/edits', query: { id: row.id } })
      },
      updateData() {
          this.$refs['dataForm'].validate((valid) => {
              if (valid) {
                  const tempData = Object.assign({}, this.temp)
                  // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
                  updateArticle(tempData).then(() => {
                      // const index = this.list.findIndex(v => v.id === this.temp.id)
                      // this.list.splice(index, 1, this.temp)
                      this.getList()
                      this.dialogFormVisible = false
                      this.$notify({
                          title: 'Success',
                          message: 'Update Successfully',
                          type: 'success',
                          duration: 2000
                      })
                  })
              }
          })
      },
      handleDelete(row, index) {
          let mup = {
              id: row.id
          }
          getDel(mup).then(response => {
              if (response.code == 200) {
                  this.$notify({
                      title: 'Success',
                      message: 'Update Successfully',
                      type: 'success',
                      duration: 2000
                  })
                  this.getList()
              } else {
                  this.$notify({
                      title: 'Success',
                      message: 'del none',
                      type: 'error',
                      duration: 2000
                  })
              }

          })



      },

      handleDownload() {
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
              const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
              const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
              const data = this.formatJson(filterVal)
              excel.export_json_to_excel({
                  header: tHeader,
                  data,
                  filename: 'table-list'
              })
              this.downloadLoading = false
          })
      },
      handleRemove(file, fileList) {
          console.log(file);
          this.temp.image = ''
      },
      handlePreview(file) {
          console.log(file);
      },
      handleonsuccess(response, file){
          console.log(file);
          this.temp.image = file.response.data
          console.log(this.temp);
      },
      formatJson(filterVal) {
          return this.list.map(v => filterVal.map(j => {
              if (j === 'timestamp') {
                  return parseTime(v[j])
              } else {
                  return v[j]
              }
          }))
      },
      getSortClass: function (key) {
          const sort = this.listQuery.sort
          return sort === `+${key}` ? 'ascending' : 'descending'
      }
  }
}
</script>

<style lang="scss" scoped>
.avatar{
  width:200px;
  height:200px;
}
</style>